package com.zhongwang.mms.module.buy.controller;

import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.common.ValidResult;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.basic.dao.DictCommonDao;
import com.zhongwang.mms.module.basic.model.DictCommon;
import com.zhongwang.mms.module.buy.model.BPreOrderPlan;
import com.zhongwang.mms.module.buy.model.PreOrderPlanImportDataModel;
import com.zhongwang.mms.module.buy.model.PreOrderPlanImportModel;
import com.zhongwang.mms.module.buy.service.BuyPreOrderPlanService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import static com.zhongwang.mms.util.GenStringUtils.formatWithMicros;

/**
 * 预购采购接口层
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/buy/preOrderPlan")
public class BuyPreOrderPlanController extends BaseController {
    @Autowired
    private BuyPreOrderPlanService buyPreOrderPlanService;
    @Autowired
    private LogService logService;
    @Autowired
    private DictCommonDao dictCommonDao;

    // 提供 getter 方法
    public BuyPreOrderPlanService getBuyPreOrderPlanService() {
        return buyPreOrderPlanService;
    }
    // 提供 getter 方法
    public LogService getLogService() {
        return logService;
    }


    /**
     * 跳转到预购计划编辑页面
     *
     * @param model
     * @return
     */
    @GetMapping("/page")
    private String page(Model model) {
        return "/buy/preOrderPlan/list/page";
    }

    /**
     * 根据用户ID获取CODE
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/getCode")
    @RequiresPermissions(value = {"buy:preorderplan:add"}, logical = Logical.OR)
    private JsonResult getCode() {
        String code = getBuyPreOrderPlanService().getNewCode();
        return JsonResult.success().setData(code);
    }

    /**
     * 查询预购计划列表
     * @param where
     * @return
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions(value = {"buy:preorderplan:view"}, logical = Logical.OR)
    public JsonResult list(BPreOrderPlan where) {
        startPage();
        List<BPreOrderPlan> list = getBuyPreOrderPlanService().findBPreOrderPlanByQuery(where);
        return jsonResult(list);
    }
    /**
     * 根据预购编号code查询预购计划列表
     * @param code 预购编号
     * @return 预购计划列表
     */
    @ResponseBody
    @PostMapping("/getProOrderPlanListByCode")
    @RequiresPermissions(value = {"buy:preorderplan:edit"}, logical = Logical.OR)
    public JsonResult getProOrderPlanListByCode(String code) {
        List<BPreOrderPlan> list = getBuyPreOrderPlanService().findBPreOrderPlanByCode(code);
        return success().setData(list);
    }

    /**
     * 根据预购计划ID判断附件文件是否存在
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/getAttachmentIsExist")
    @RequiresPermissions(value = {"buy:preorderplan:download"}, logical = Logical.OR)
    public JsonResult getAttachmentIsExist(Integer id) {
        BPreOrderPlan preOrderPlan = getBuyPreOrderPlanService().getBPreOrderPlanByPrimaryKey(id);
        String attachmentUrl = preOrderPlan.getAttachment();
        String msg = "有文件";
        if(attachmentUrl == null || attachmentUrl.equals("")){
            msg = "没有文件";
        }else{
            attachmentUrl = attachmentUrl.replace("/files/", "/");
            String localPath = uploadPath + attachmentUrl.substring(attachmentUrl.indexOf("/"));
            if(new File(localPath).exists()) {
                return success(msg);
            }
        }
        return error(msg);
    }

    /**
     * 根据预购编号提交预购计划
     * @param code
     * @return
     */
    @ResponseBody
    @PostMapping("/submitByCodes")
    @RequiresPermissions(value = {"buy:preorderplan:submit"}, logical = Logical.OR)
    public JsonResult submitByCodes(@RequestParam("codes[]") List<String> codes) {
        Integer res = getBuyPreOrderPlanService().submitByCodes(codes);
        if(res > 0){
            return success("提交成功！");
        }
        return error("提交失败！");
    }
    /**
     * 根据预购编号删除预购计划
     * @param code
     * @return
     */
    @ResponseBody
    @PostMapping("/deleteByCodes")
    @RequiresPermissions(value = {"buy:preorderplan:delete"}, logical = Logical.OR)
    public JsonResult deleteByCodes(@RequestParam("codes[]") List<String> codes) {
        Integer res = getBuyPreOrderPlanService().deleteByCodes(codes);
        if(res > 0){
            return success("删除成功！");
        }
        return error("删除失败！");
    }
    /**
     * 根据预购计划ID下载附件
     * @param id 预购计划ID
     */
    @GetMapping("/downloadAttachment/{id}")
    @RequiresPermissions(value = {"buy:preorderplan:download"}, logical = Logical.OR)
    public ResponseEntity<Resource> downloadAttachment(@PathVariable("id") Integer id,
                                                       HttpServletResponse httpServletResponse,
                                                       HttpServletRequest request) throws MalformedURLException {
            BPreOrderPlan preOrderPlan = getBuyPreOrderPlanService().getBPreOrderPlanByPrimaryKey(id);
            String attachmentUrl = preOrderPlan.getAttachment();
            attachmentUrl = attachmentUrl.replace("/files/", "/");
            String localPath = uploadPath + attachmentUrl.substring(attachmentUrl.indexOf("/"));
            Path realPath = Paths.get(localPath); // 真实文件
            Resource resource = new UrlResource(realPath.toUri());
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }else{
                // 根据浏览器类型决定编码方式
                String agent = request.getHeader("User-Agent");
                String disposition = "attachment; filename*=UTF-8''" + UriUtils.encode(preOrderPlan.getAttachmentName(), StandardCharsets.UTF_8);
                getLogService().saveLog("采购管理-预购计划编辑", "下载预购主题为：" + preOrderPlan.getName() + "，预购编码为：" + preOrderPlan.getCode() + ",物料跟踪码为：" + preOrderPlan.getTrackNumber() + ",物料描述为：" + preOrderPlan.getMaterialDesc() + "的名称为：" + preOrderPlan.getAttachmentName() + "的附件（附件大小：" + FileUtils.formatFileSize(realPath.toFile().length()) + "）！");
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, disposition)
                        .body(resource);
            }
    }

    /**
     * 上传文件路径
     */
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 创建-保存预购计划单
     */
    @ResponseBody
    @PostMapping("/importExcel")
    @RequiresPermissions(value = {"buy:preorderplan:add"}, logical = Logical.OR)
    public JsonResult importExcel(@ModelAttribute PreOrderPlanImportModel data) {
        if(data.getRows().size() > 0){
            //拆解模型，拼装成可以存储进数据库的模型
            List<BPreOrderPlan> bPreOrderPlanList = new ArrayList();
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            for (int i = 0; i < data.getRows().size(); i++) {
                PreOrderPlanImportDataModel popidm = data.getRows().get(i);
                BPreOrderPlan bPreOrderPlan = new BPreOrderPlan();
                bPreOrderPlan.setName(data.getName());
                bPreOrderPlan.setCode(data.getCode());
                bPreOrderPlan.setMaterialDesc(popidm.getMaterialDesc());
                bPreOrderPlan.setMaterialCode(popidm.getMaterialCode());
                bPreOrderPlan.setProCode(popidm.getProCode());
                bPreOrderPlan.setProName(popidm.getProName());
                bPreOrderPlan.setPurchaser(popidm.getPurchaser());
                bPreOrderPlan.setNum(new BigDecimal(popidm.getNum()));
                bPreOrderPlan.setUnit(popidm.getUnit());
                bPreOrderPlan.setPreOrderRemark(popidm.getPreOrderRemark());
                bPreOrderPlan.setModel(popidm.getModel());
                bPreOrderPlan.setBrand(popidm.getBrand());
                bPreOrderPlan.setRejectReason("");
                //分析上传文件进行上传文件，将上传完毕的文件的相对路径更新到存储到数据库对应的字段
                if (popidm.getUploadFile() != null) {
                    String path = uploadPath + "/preOrderPlan/";
                    String fileNameNotHaveFileExtension = FileUtils.getFileNameWithoutExtension(popidm.getUploadFile().getOriginalFilename());
                    String fileExtension = FileUtils.getFileExtension(popidm.getUploadFile().getOriginalFilename());
                    String newFileName = fileNameNotHaveFileExtension + formatWithMicros(new Date()) +"."+fileExtension;
                    String fileName = FileUtils.uploadGenDiyFileName(popidm.getUploadFile(), path, newFileName);
                    String url = "/files/preOrderPlan/" + fileName;
                    bPreOrderPlan.setAttachment(url);
                    bPreOrderPlan.setAttachmentName(fileNameNotHaveFileExtension + "." + fileExtension);
                }
                bPreOrderPlanList.add(bPreOrderPlan);
            }
            Integer res = getBuyPreOrderPlanService().saveImportExcelData(bPreOrderPlanList);
            if (res > 0) {
                getLogService().saveLog("采购管理-预购计划编辑","添加预购清单，预购清单编号为："+data.getCode()+"，明细数共"+data.getRows().size()+"条数据！");
                return JsonResult.success("保存成功！");
            }else{
                return JsonResult.fail("保存失败，请通知管理员！");
            }
        }else{
            return JsonResult.fail("保存失败，请导入或填写预购清单！");
        }
    }


    /**
     * 修改-保存预购计划单
     */
    @ResponseBody
    @PostMapping("/importExcelForUpdate")
    @RequiresPermissions(value = {"buy:preorderplan:edit"}, logical = Logical.OR)
    public JsonResult importExcelForUpdate(@ModelAttribute PreOrderPlanImportModel data) {
        if(data.getRows().size() > 0){
            Integer res = getBuyPreOrderPlanService().importExcelForUpdate(data);
            if (res > 0) {
                getLogService().saveLog("采购管理-预购计划编辑","修改预购清单，预购清单编号为："+data.getCode()+"，明细数共"+data.getRows().size()+"条数据！");
                return JsonResult.success("保存成功！");
            }else{
                return JsonResult.fail("保存失败，请通知管理员！");
            }
        }else{
            return JsonResult.fail("保存失败，请导入或填写预购清单！");
        }
    }

    /**
     * 检查项目号是否存在
     *
     * @param proCode 项目号
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/checkProjectCode")
    @RequiresPermissions({"buy:planimport:view"})
    public ValidResult checkProjectCode(String proCode) {
        boolean exist = getBuyPreOrderPlanService().getProjectByCode(proCode);
        return exist ? ValidResult.SUCCESS : ValidResult.FAIL;
    }

    /**
     * 获取用来被指派的采购科的业务员
     * @return
     */
    @ResponseBody
    @PostMapping("/getAssignPurchaserList")
    @RequiresPermissions({"buy:preorderplan:assign"})
    public JsonResult  getAssignPurchaserList() {
        JsonResult res = new JsonResult();
        res.setData(getBuyPreOrderPlanService().findSysUserListByDeptName("采购科"));
        res.success("成功！");
        return res;
    }


    /**
     * 指派
     * @param code 被指派预购编号
     * @param assignPurchaserId 被指派的业务员ID
     * @return
     */
    @ResponseBody
    @PostMapping("/assign")
    @RequiresPermissions({"buy:preorderplan:assign"})
    public JsonResult assign(String code,Integer assignPurchaserId) {
        Integer res = getBuyPreOrderPlanService().assign(code,assignPurchaserId);
        if (res > 0) {
            return success("指派成功");
        }
        return error("指派失败");
    }

    /**
     * 驳回计划
     * @param codes 驳回的预购编号
     * @param rejectReason 驳回原因
     * */
    @ResponseBody
    @PostMapping("/reject")
    @RequiresPermissions({"buy:preorderplan:assign"})
    public JsonResult reject(@RequestParam("codes") List<String> codes,String rejectReason) {
        return jsonResult(getBuyPreOrderPlanService().reject(codes,rejectReason));
    }
}
